// +----------------------------------------------------------------------
// | BossHongshi [鸿时互娱管理系统]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hongshihuyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wgh
// +----------------------------------------------------------------------
const fly=require("flyio")
const HashMap = require('hashmap')
module.exports = class extends think.cmswing.center {
  /**
     * 注册页面
     */
  async registerAction() {
    if (this.isPost) {
      const data = this.post();
      // console.log(data);
      // 验证
      //data.game_id)&&!think.isEmpty(data.iagentid
      let res;
      if (think.isEmpty(data.iagentid)) {
          return this.fail('邀请人代理ID不能为空！');
      }
      if (think.isEmpty(data.game_id)) {
          return this.fail('本人游戏ID不能为空！');
      }else {
          var gameidmember = await this.model('member').where({game_id: data.game_id}).find();
          if (!think.isEmpty(gameidmember)) {
            return this.fail('本人游戏ID已存在，请重新填写！');
          }
      }
      
      if (think.isEmpty(data.mobile)) {
        return this.fail('手机号码不能为空！');
      } else {
        res = await this.model('member').where({mobile: data.mobile}).find();
        if (!think.isEmpty(res)) {
          return this.fail('手机号码已存在，请重新填写！');
        }
      }
      var vcres;
      if (think.isEmpty(data.verifcode)) {
        return this.fail('手机验证码不能为空！');
      } else {
        vcres = await this.model('sms_verifcode').where({mobile:data.mobile,validate_code:data.verifcode,type:'1',status:0}).find();
        console.log('验证码vcres ------------------:'+JSON.stringify(vcres));
        var exp_time = new Date().valueOf();
        if(think.isEmpty(vcres)) {
          return this.fail('手机验证码错误!');
        }else if(exp_time>vcres.expire_time){
          await this.model('sms_verifcode').where({id:vcres.id}).update({status:-1});
          return this.fail('手机验证码已失效!');
        }
      }

      if (think.isEmpty(data.password) && think.isEmpty(data.password2)) {
        return this.fail('密码不能为空！');
      } else {
        if (data.password != data.password2) {
          return this.fail('两次输入的密码不一致，请重新填写！');
        }
      }
      if (data.clause != 'on') {
        return this.fail('必须要同意,用户代理协议');
      }
      
      
      //数据状态 0禁用，1启用，-1删除
      console.log('data.iagentid ------------------:'+JSON.stringify(data.iagentid));
      const pdata = await this.model('member').where({proxy_id:data.iagentid}).find();
      console.log('pdata ------------------:'+think.isEmpty(pdata)?null:JSON.stringify(pdata));
      if(!think.isEmpty(pdata)){
    	  if(pdata.groupid<3){
    		  if(pdata.status==0){
            	  return this.fail('邀请人代理ID已禁用,请联系客服！');
              }else if(pdata.status==-1){
            	  return this.fail('邀请人代理ID已删除,请联系客服！');
              }else if(pdata.status==1){
            	  if(pdata.is_admin==1){
            	     data.groupid=1;
            	  }else if(pdata.is_admin==0){
            		 data.groupid=Number(pdata.groupid)+1;
            	  }
              }  
    	  }else{
    		  return this.fail('邀请人代理ID不能授权下级代理,请联系客服！');
    	  }
      }else{
    	  return this.fail('邀请人代理ID不存在,请联系客服！');
      }
      
      const timestr = new Date().getTime().toString();
      const subid = timestr.substr(6);
      
      const url='http://47.97.119.70:5166/GameSupport/dn?cmd=bindByUid&uid='+data.game_id+'&agentId='+subid+'&invagentId='+data.iagentid+'&sign=password';
      console.log('绑定代理id--url---------:'+url);
      fly.config.timeout=10000;
	  fly.config.parseJson=true;
	  fly.interceptors.response.use(
		 (response) => {
						        //只将请求结果的data字段返回
			return response.data
		 },
		 (err) => {
				//发生网络错误后会走到这里
				//return Promise.resolve("ssss")
		 }
	  )
	  let ret = await fly.get(url).catch(() => false);
	  console.log('bindByUid ret------------------:'+ret);
	  let retjson = (ret === false?null:JSON.parse(ret));
	  if(retjson!=null&&retjson.data.result!=0){
	  		return this.fail(retjson.data.msg);
	  }else{
	  		data.username = subid;
	        data.proxy_id = subid;
            data.avatar = retjson.data.headimgurl;
            data.addr = retjson.data.LastLoc;
            data.nick_name = retjson.data.nickname;
	        data.ia_uname = data.iagentid;
	        data.zoning = pdata.zoning;
	        data.area = pdata.area;
	        data.status = 1;
	        data.reg_time = new Date().valueOf();
	        data.reg_ip = _ip2int(this.ip);
	        data.password = encryptPassword(data.password);
            const reg = await this.model('member').add(data);
            
            await this.model('cmswing/member').autoLogin({id: reg}, this.ip);// 更新用户登录信息，自动登陆
	        const userInfo = {
	          'uid': reg,
	          'username': data.username,
	          'last_login_time': data.reg_time
	        };
            await this.session('webuser', userInfo);
          
            await this.model('sms_verifcode').where({id:vcres.id}).update({status:1});
          
	        return this.success({name: '注册成功,登录中!', url: '/center/index'});
	  	 }
    } else {
      this.meta_title = '用户注册';
      // 短信注册视图钩子
      await this.hook('smsRegistration');
      // 第三方登录钩子
      await this.hook('logins');
      return this.isMobile ? this.display(this.mtpl()) : this.display();
    }
  }
  
    //   登陆页面
  async indexAction() {
      
      this.meta_title = '首页';

      // 判断浏览客户端
      if (this.isMobile) {
        this.active = 'center/index';
        return this.display(this.mtpl());
      } else {
        return this.display();
      }
  }
  //   登陆页面
  async loginAction() {
    // 判断公众账号类型
	
    // if (this.config('setup.wx_type') == 4 || this.config('setup.wx_type') == 2) {
    //   await this.action('center/weixin', 'oauth');
    // }
	  
//	  console.log("generateUUID() 1:"+generateUUID());
//	  console.log("generateUUID() 2:"+generateUUID());
//	  var signStr="appid=3012d27c-1ba9-4051-9511-9c5b29a19b83&username=ceshi&password=123456&loginType=device&deviceType=IOS&deviceName=mac&resolution=1136x640&version=2.0.14&osVersion=macOS&deviceToken=0b9987989e1fbe4930d163c85edca2fd78f52e18630127e7-8f2c-454c-81a1-94def0a02fc7";
//	  signStr=think.md5(signStr);
//	  console.log("signStr--:"+signStr);
//	  console.log("GetDateStr(-1)-:"+GetDateStr(-1));
	  
    if (this.isAjax('post')) {
      // 验证码 钩子
      const signinBefore = await this.hook('loginBefore');
      if (signinBefore === 'no') {
        return this.fail(-3, '验证码不正确!');
      }
      // 用户账号密码验证
      const username = this.post('username');
      let password = this.post('password');
      password = encryptPassword(password);
      const res = await this.model('cmswing/member').signin(username, password, this.ip, 5, 0);
      // 钩子
      if (res.uid > 0) {
        // 记录用户登录行为
        // await this.model("action").log("user_login", "member", res.uid, res.uid, this.ip(), this.http.url);
        // console.log(111111111111121);
        // console.log(res);
        await this.session('webuser', res);
        // TODO 用户密钥
        return this.success({name: '登录成功！'});
      } else { // 登录失败
        let fail;
        switch (res) {
          case -1:
            fail = '用户不存在或被禁用';
            break; // 系统级别禁用
          case -2:
            fail = '密码错误';
            break;
          default:
            fail = '未知错误';
            break; // 0-接口参数错误（调试阶段使用）
        }
        return this.fail(res, fail);
      }
    } else {
      // 如果已经登陆直接跳转到用户中心
      if (this.is_login) {
        return this.redirect('/center/index');
      }
      
//      var deadline = await this.model('setup').where({name:'PROFIT_DEADLINE'}).getField('value', true);
//	  console.log('上次分润处理截至时间--:'+deadline);
//	  var timeperiod = await this.model('setup').where({name:'PROFIT_TIMEPERIOD'}).getField('value', true);
//	  console.log('下次分润处理时间区间--:'+timeperiod);
//	  var hoursec = parseInt(deadline)+parseInt(timeperiod);
//	  console.log('一个小时后秒时间--:'+hoursec);
//	  let scorelog = this.mongoose('jb_scorelog', 'mongoose'); // use `mongoose` adapter type
//	  let scorelogdata  = await scorelog.find({reffer_id: {$ne:0 },create_time:{$gt:parseInt(deadline),$lte:parseInt(hoursec)}}).sort({'create_time':1}).lean().exec();
//	  console.log("scorelogdata---:"+JSON.stringify(scorelogdata));
//      console.log("scorelogdata.length---:"+scorelogdata.length);
//
//     var map = new HashMap();
//  	 for (const v of scorelogdata) {
//  		if(!map.has(v.uid)){
//  			let profitObj = {}; 
//  			profitObj.starttime = v.create_time;
//  			profitObj.endtime = v.create_time;
//  			profitObj.reffer_id = v.reffer_id;
//  			profitObj.cost = v.cost;
//  			profitObj.ctime = v.ctime;
//  			profitObj.room_id=v.room_id;
//  			profitObj.id = v.id;
//  			profitObj.lid = v.id;
//  			console.log("profitObj-1-cost: "+ profitObj.cost);
//  			map.set(v.uid,profitObj);
//  		}else{
//  			var profitObj = map.get(v.uid);
//  			profitObj.endtime = v.create_time;
//  			console.log("profitObj-s-cost: "+ profitObj.cost);
//  			console.log("profitObj-+-cost: "+ v.cost);
//  			profitObj.cost = parseInt(profitObj.cost)+parseInt(v.cost);
//  			profitObj.ctime = v.ctime;
//  			profitObj.room_id=profitObj.room_id+","+v.room_id;
//  			profitObj.id = profitObj.id+","+v.id;
//  			profitObj.lid = v.id;
//  			console.log("profitObj-e-cost: "+ profitObj.cost);
//  		}
//  	}
//  	
//  	map.forEach(function(value, key) {
//  	    console.log("map取值-key: "+key + " value : " + JSON.stringify(value));
//  	});
  	
      this.meta_title = '用户登录';
      // 第三方登录钩子
      await this.hook('logins');
      // 登录验证视图钩子
      await this.hook('loginView');
      
      // 判断浏览客户端
      if (this.isMobile) {
        this.active = 'center/index';
        return this.display(this.mtpl());
      } else {
        return this.display();
      }
    }
  }
  // 退出登录
  async logoutAction() {
    // 退出登录

    if (this.is_login) {
      await this.session('webuser', null);
      // 清楚cy_id
      // await this.session("wx_openid",null);
      // cysoIp9AH
//      return this.display();
      return this.redirect('/login');
    } else {
      return this.redirect('/login');
    }
  }
  
  /**
   * 邀请绑定页面
   */
async bindingAction() {
  if (this.isPost) {
    const data = this.post();
    // console.log(data);
    // 验证
    let res;
    if (think.isEmpty(data.mobile)) {
      return this.fail('手机号码不能为空！');
    } else {
      res = await this.model('member').where({mobile: data.mobile}).find();
      if (!think.isEmpty(res)) {
        return this.fail('手机号码已存在，请重新填写！');
      }
    }
    if (think.isEmpty(data.password) && think.isEmpty(data.password2)) {
      return this.fail('密码不能为空！');
    } else {
      if (data.password != data.password2) {
        return this.fail('两次输入的密码不一致，请重新填写！');
      }
    }
    if (data.clause != 'on') {
      return this.fail('必须要同意,用户代理协议');
    }
    const timestr = new Date().getTime().toString();
    data.username = timestr.substr(5);
    data.status = 1;
    data.reg_time = new Date().valueOf();
    data.reg_ip = _ip2int(this.ip);
    data.password = encryptPassword(data.password);
    const reg = await this.model('member').add(data);
    await this.model('cmswing/member').autoLogin({id: reg}, this.ip);// 更新用户登录信息，自动登陆
    const userInfo = {
      'uid': reg,
      'username': data.username,
      'last_login_time': data.reg_time
    };
    await this.session('webuser', userInfo);
    return this.success({name: '绑定成功!', url: '/center/index'});
  } else {
    this.meta_title = '玩家绑定';
    const invid = this.para('invid') || null;
    let member = await this.model('member').where({username:invid}).find();
    const userInfo = {
    	      'uid': member.id,
    	      'username': member.username
    };
    this.assign('userInfo', userInfo);
    return this.isMobile ? this.display(this.mtpl()) : this.display();
  }
 }
 
//   下载页面
async downAction() {
	this.meta_title = '下载';
    return this.isMobile ? this.display(this.mtpl()) : this.display();
}

//下载页面
async setupAction() {
	this.meta_title = 'IOS安装说明';
    return this.isMobile ? this.display(this.mtpl()) : this.display();
}

/**
* 重置密码页面
*/
async resetpwdAction() {
    if (this.isPost) {
      const data = this.post();
      // 验证
      let res;
      
      if (think.isEmpty(data.mobile)) {
        return this.fail('手机号码不能为空！');
      } 
      var vcres;
      if (think.isEmpty(data.verifcode)) {
        return this.fail('手机验证码不能为空！');
      } else {
        vcres = await this.model('sms_verifcode').where({mobile:data.mobile,validate_code:data.verifcode,type:'2',status:0}).find();
        console.log('验证码vcres ------------------:'+JSON.stringify(vcres));
        var exp_time = new Date().valueOf();
        if(think.isEmpty(vcres)) {
          return this.fail('手机验证码错误!');
        }else if(exp_time>vcres.expire_time){
          await this.model('sms_verifcode').where({id:vcres.id}).update({status:-1});
          return this.fail('手机验证码已失效!');
        }
      }

      if (think.isEmpty(data.password) && think.isEmpty(data.password2)) {
        return this.fail('新密码不能为空！');
      } else {
        if (data.password != data.password2) {
          return this.fail('两次输入的密码不一致，请重新填写！');
        }
        //data.password = encryptPassword(data.password);
      }

      //数据状态 0禁用，1启用，-1删除
      const pdata = await this.model('member').where({mobile:data.mobile}).find();

      if(!think.isEmpty(pdata)){
    	if(pdata.status==0){
          return this.fail('账号已禁用,请联系客服！');
        }else if(pdata.status==-1){
          return this.fail('账号已删除,请联系客服！');
        }  
      }else{
    	  return this.fail('账号不存在,请联系客服！');
      }

      let update = await this.model('member').where({id:pdata.id,mobile:data.mobile}).update({password:encryptPassword(data.password)});
      
	  if(think.isEmpty(update)){
	  		return this.fail('重置密码失败！');
	  }else{
            await this.model('sms_verifcode').where({id:vcres.id}).update({status:1});
	        return this.success({name: '重置成功,返回首页登录!', url: '/center/index'});
	  }
    } else {
      this.meta_title = '找回密码';
      return this.isMobile ? this.display(this.mtpl()) : this.display();
    }
  }
};
